package com.sso.core.ssoauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sso.core.ssoauth.dao.*;
import com.sso.core.ssoauth.domain.LoginAppUser;
import com.sso.core.ssoauth.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/11/21/20:28
 */
@Service
public class UserServiceImpl extends ServiceImpl<SysDao, SysUser>implements UserService {
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysUserRoleDao sysUserRole;
    @Resource
    private SysPermissionDao sysPermissionDao;
    @Resource
    private SysRolePermissionDao sysRolePermissionDao;


    @Override
    public LoginAppUser findByUsername(String username) {
        SysUser appUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername,username));
        if (appUser != null) {
            LoginAppUser loginAppUser = new LoginAppUser();
            BeanUtils.copyProperties(appUser, loginAppUser);
            List<SysUserRole> roles = sysUserRole.selectList(new QueryWrapper<SysUserRole>().
                    lambda().
                    eq(SysUserRole::getUserId, loginAppUser.getId()));
            Set<SysRole> sysRoles = null;
            if (!CollectionUtils.isEmpty(roles)){
              sysRoles = sysRoleDao.selectList(new QueryWrapper<SysRole>().lambda().in(SysRole::getId, roles.
                        stream().map(SysUserRole::getRoleId
                ).collect(Collectors.toList()))).stream().collect(Collectors.toSet());
            }
            loginAppUser.setSysRoles(sysRoles);// 设置角色
            if (!CollectionUtils.isEmpty(sysRoles)) {
                List<SysRolePermission> perm = sysRolePermissionDao.
                        selectList(new QueryWrapper<SysRolePermission>().lambda().in(SysRolePermission::getRoleId
                        , sysRoles.stream().map(SysRole::getId).collect(Collectors.toSet())));
                Set<SysPermission> sysPermissions = sysPermissionDao.selectBatchIds(perm.stream()
                        .map(SysRolePermission::getPermissionId)
                        .collect(Collectors.toList())).stream().collect(Collectors.toSet());
                if (!CollectionUtils.isEmpty(sysPermissions)) {
                    Set<String> permissions = sysPermissions.parallelStream().map(SysPermission::getUri)
                            .collect(Collectors.toSet());
                    loginAppUser.setPermission(permissions);// 设置权限集合
                }
            }

            return loginAppUser;
        }

        return null;
    }
}
